const enterpriseVue = new Vue({
  el: '#app',
  data() {
    return {
      form: {
        Integral_Unit_Price_SerialNumber: "",
        Start_Date: "",
        End_Date: "",
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Children: {
          integral_unitprice_detail: [
            {
              Integral_Unit_Price_Detail_SerialNumber: "",
              Integral_Unit_Price_SerialNumber: "",
              Article_SerialNumber: "",
              Article_Specifications_SerialNumber: "",
              Unit_Price: "",
              Integral_Unit_Price: "",
              Sign: "无货货主",
              specs: [],//商品规格
              Distribute: '',
              Warehouse: [],
              sWarehouse: [],
              Children: {
                integral_unitprice_stock: [
                ]
              }
            }
          ],
          integral_unitprice_storescope: [
            {
              Integral_Unit_Price_StoreScope_SerialNumber: "",
              Integral_Unit_Price_SerialNumber: "",
              Store_SerialNumber: "",
            }
          ],
          integral_unitprice_column: [{
            Integral_Unit_Price_Column_SerialNumber: '',
            Integral_Unit_Price_SerialNumber: '', //单价流水号
            ShopColumn_Id: '',  //栏目流水号
            Column_Type: '', //栏目属性
          }]
        }
      },
      loading: false,
      dialogVisible: false,
      Start_Date: "",
      End_Date: "",
      Column_Id: [],
      ColumnData:[],
      fileList: [],
      shop: [],
      column: [],
      ShopColumn_Id: [],
      tableData: [],
      Enterprise: [],
      isDisabled: true,
      Distribute: 0,//分配数量
      store: [],//适用店铺
      always: "00:00:00",//补货时间
      rules: {
        Start_Date: [
          { required: true, message: '请输入开始时间', trigger: 'blur' },
        ],
        End_Date: [
          { required: true, message: '请输入结束时间', trigger: 'change' }
        ],
        // always: [
        //   { required: true, message: '请输入补货时间', trigger: 'change' }
        // ],
        // pp: [
        //   { required: true, message: '请选择商品分类方式', trigger: 'blur' }
        // ],
        // zhongli: [
        //   { required: true, message: '请选择适用商品类', trigger: 'blur' }
        // ],
      },
      Article_SerialNumber: [
        { required: true, message: '请选择商品', trigger: 'change' }
      ],
      Article_Specifications_SerialNumber: [
        { required: true, message: '请选择规格', trigger: 'change' }
      ],
      Integral_Unit_Price: [
        { required: true, message: '请输入所需积分', trigger: 'change' }
      ],
      Distribute: [
        { required: true, message: '请输入分配数量', trigger: 'change' }
      ],
      Store_SerialNumber: [
        { required: true, message: '请输入适用店铺', trigger: 'change' }
      ],
    }
  },
  mounted() {
    this.getData()
  },
  computed: {
    Column() {
      return function (Column_Name) {
        let obj = this.column.filter((item, index) => {
          return Column_Name == item.Column_Name
        })[0]
        return obj.Column_Id
      }
    },
    // Article() {
    //   return function (name) {
    //     let obj = this.shop.filter((item, index) => {
    //       return name == item.Article_Name
    //     })[0]
    //     return obj.Article_SerialNumber
    //   }
    // },
    Unit_Price() {
      return function (name) {
        let obj = this.shop.filter((item, index) => {
          return name == item.Article_Name
        })[0]
        return obj.Unit_Price
      }
    },
    formatTime() {
      return function (time) {
        let d = new Date(time);
        let year = d.getFullYear();
        let month = d.getMonth() + 1
        let day = d.getDate()
        let hour = d.getHours()
        let minute = d.getMinutes()
        let second = d.getSeconds()
        if (month < 10) { month = '0' + month }
        if (day < 10) { day = '0' + day }
        if (hour < 10) { hour = '0' + hour }
        if (minute < 10) { minute = '0' + minute }
        if (second < 10) { second = '0' + second }
        return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
      };
    },
  },
  methods: {
    //适用店铺
    add_integral_scheme_storescope() {
      this.form.Children.integral_unitprice_storescope.push({
        Integral_Unit_Price_StoreScope_SerialNumber: "",
        Integral_Unit_Price_SerialNumber: "",
        Store_SerialNumber: "",
      })
    },
    remove_integral_scheme_storescope() {
      if (this.form.Children.integral_unitprice_storescope.length > 1) {
        this.form.Children.integral_unitprice_storescope.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    ChangeRadio(e, index) {
      console.log(e, index)
      this.form.Children.integral_unitprice_detail[index].Article_SerialNumber = ''
      this.form.Children.integral_unitprice_detail[index].Article_Specifications_SerialNumber = ''
      this.form.Children.integral_unitprice_detail[index].Unit_Price = ''
      this.form.Children.integral_unitprice_detail[index].Net_Content = ''
      this.form.Children.integral_unitprice_detail[index].Integral_Unit_Price = ''
      this.form.Children.integral_unitprice_detail[index].specs = []
      this.form.Children.integral_unitprice_detail[index].isWarehouse = []
      this.form.Children.integral_unitprice_detail[index].Warehouse = []
    },
    validateEnd_Date(rule, value, callback) {
      if (+new Date(value) < +new Date(this.form.Start_Date)) {
        callback(new Error('结算时间不能小于开始时间'));
      } else {
        callback();
      }
    },
    // 新增积分销售价格单明细
    add_integral_unitprice_detail() {
      this.form.Children.integral_unitprice_detail.push({
        Integral_Unit_Price_Detail_SerialNumber: "",
        Integral_Unit_Price_SerialNumber: "",
        Article_SerialNumber: "",
        Article_Specifications_SerialNumber: "",
        Unit_Price: "",
        Integral_Unit_Price: "",
        Sign: "无货货主",
        Distribute: '',
        specs: [],
        Warehouse: [],
        Children: {
          integral_unitprice_stock: [
          ]
        }
      })
    },
    remove_integral_unitprice_detail() {
      if (this.form.Children.integral_unitprice_detail.length > 1) {
        this.form.Children.integral_unitprice_detail.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    add_integral_unitprice_column() {
      this.form.Children.integral_unitprice_column.push({  //栏目
        Integral_Unit_Price_Column_SerialNumber: '',
        Integral_Unit_Price_SerialNumber: '', //单价流水号
        ShopColumn_Id: '',  //栏目流水号
        Column_Type: '', //栏目属性
      })
    },
    remove_integral_unitprice_column() {
      if (this.form.Children.integral_unitprice_column.length > 1) {
        this.form.Children.integral_unitprice_column.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
    fetch(item){
      console.log('获取的数据',item.App_ID)
      if(!this.ColumnData.some((App_ID
        )=>{
          App_ID==item.App_ID
      })){
        this.ColumnData.push(item.App_ID)
      }
      console.log(this.ColumnData)
      this.getShop()
    },
    beforeRemove() {
      this.fileList.pop()
      this.tableData = []
    },
    uploadDetails(file) {
      this.fileList.push({
        name: file.name,
        url: file.type
      })
      const _this = this
      var reader = new FileReader();
      reader.readAsBinaryString(file);
      reader.onload = function (e) {
        var data = e.target.result;
        var wb = XLSX.read(data, {
          type: 'binary' //以二进制的方式读取
        });
        var sheet0 = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
        var json = XLSX.utils.sheet_to_json(sheet0);//利用接口实现转换。
        console.log(json);
        let arr = []
        json.forEach(item => {
          // let Article = _this.isShop(item['品名'])
          // let Abnormal = [Article.abnormal]
          arr.push({
            Integral_Unit_Price_Detail_SerialNumber: "",
            Integral_Unit_Price_SerialNumber: '',
            Article_Specifications_SerialNumber: '',
            // Article_SerialNumber: Article.Article_SerialNumber,
            Unit_Price: item['金额'],
            Integral_Unit_Price: item['积分'],
            Sign: item['有/无货货主'],
            Distribute: item['数量'],
            Abnormal: !Abnormal.some(item => item == false),
            Children: {
              integral_unitprice_stock: []
            }
          })
        })
        _this.tableData = arr
      }
    },
    isShop(str) {
      if (this.shop.some(item => item.Article_Name == str)) {
        return { Article_SerialNumber: this.shop.filter(item => item.Article_Name == str)[0].Brand_SerialNumber, abnormal: true }
      } else {
        return { Article_SerialNumber: '异常数据(未找到' + str + ')', abnormal: false }
      }
    },
    //请求商品
    getData() {
      let _this = this;
      $.ajax({
        type: 'POST',
        url: DomainName + "/getInquiryAction",
        data: {
          Data: "store_info",
          token: $.cookie("token"),
          
        },
        success: function (res) {
          res = res.filter(function (item) {
            return item.Row_Status != '1'
          })
          for (let i = 0; i < res.length; i++) {
            _this.store.push(res[i]);
          }
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      $.ajax({
        url: DomainName + '/getInquiryIDAction?token=' + $.cookie("token"),
        type: 'POST',
        data: {
          Primary_Key_Name: 'Activity',
          Primary_Key: '0',
          Data: 'column_main',
        },
        success: function (res) {
          _this.column = res;
          console.log('1111',_this.column)
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
      $.ajax({
        url: DomainName + '/getSalesArticleInfoAction',
        type: 'POST',
        data: { token: $.cookie("token") },
        success: function (res) {
          console.log(res)
          _this.shop = res
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    getShop(){
      const _this = this
      $.ajax({
        type: 'POST',
        url: DomainName + "/getStoreAction?token="+ $.cookie("token"),
        data: {
          Data: JSON.stringify(_this.ColumnData),
        },
        success: function (res) {
          if(res.Status == 'success'){
            _this.store = res.Data
          }
          console.log(res)
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
    }, 
    onExcel() {
      this.dialogVisible = true
    },
    //商品规格数据
    Change_Unit_Price(index,Sign) {
      // this.isDisabled = true
      console.log(this.shop[index].Article_SerialNumber);
      let str = this.form.Children.integral_unitprice_detail[index].Article_SerialNumber
      this.form.Children.integral_unitprice_detail[index].Article_Specifications_SerialNumber = ''
      let _this = this;
      $.ajax({
        type: 'POST',
        url: DomainName + "/SpecificationsIDAction",
        data: {
          Article_SerialNumber: str,
          token: $.cookie("token")
        },
        success: function (res) {
          _this.form.Children.integral_unitprice_detail[index].specs = res
          console.log(res)
          _this.isDisabled = false
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        dataType: "json"
      });
      if (Sign == '有货货主') {
        $.ajax({
          url: DomainName + '/getWarehouseGoodsID?token=' + $.cookie("token"),
          type: 'POST',
          data: {
            Article_SerialNumber: str,
          },
          success: function (res) {
            console.log(res)
            if (res.Data.length > 0) {
              _this.form.Children.integral_unitprice_detail[index].Warehouse = res.Data
            }
          }
        })
      }
    },
    Change_Specifications_Name(index) {//吊牌价
      let str = this.form.Children.integral_unitprice_detail[index].Article_Specifications_SerialNumber
      console.log(str)
      console.log(this.form.Children.integral_unitprice_detail[index].specs[0])
      for (let i = 0; i < this.form.Children.integral_unitprice_detail[index].specs.length; i++) {
        console.log(this.form.Children.integral_unitprice_detail[index].specs[i].Article_Specifications_SerialNumber)
        if (this.form.Children.integral_unitprice_detail[index].specs[i].Article_Specifications_SerialNumber == str) {
          this.form.Children.integral_unitprice_detail[index].Net_Content = this.form.Children.integral_unitprice_detail[index].specs[i].Net_Content
          this.form.Children.integral_unitprice_detail[index].Unit_Price = this.form.Children.integral_unitprice_detail[index].specs[i].Unit_Price
        }
      }
    },
    Automatic(item, Store_SerialNumber, Start_Date, End_Date, time) {
      console.log(item, Start_Date, End_Date, time);
      //一天毫秒数
      let TimeDays = (1000 * 60) * 60 * 24
      if (+new Date(End_Date) <= +new Date(time)) {//若结算时间小于次日补货时间
        item.Children.integral_unitprice_stock.push({
          Integral_Unit_Price_Stock_SerialNumber: "",
          Integral_Unit_Price_Detail_SerialNumber: "",
          Store_SerialNumber,
          Start_Date: Start_Date,
          End_Date: End_Date,
          Distribute: parseInt(item.Distribute),
          Stock_Remain: parseInt(item.Distribute),
          Stock_Sell: 0
        })
      } else {//若结算时间大于次日补货时间
        item.Children.integral_unitprice_stock.push({
          Integral_Unit_Price_Stock_SerialNumber: "",
          Integral_Unit_Price_Detail_SerialNumber: "",
          Store_SerialNumber,
          Start_Date: Start_Date,
          End_Date: this.formatTime(+new Date(time) - 1000),
          Distribute: parseInt(item.Distribute),
          Stock_Remain: parseInt(item.Distribute),
          Stock_Sell: 0,
        })
        this.Automatic(item, Store_SerialNumber, time, End_Date, this.formatTime(+new Date(time) + TimeDays))
      }
    },
    submitForm(formName) {
      let _this = this
      //
      console.log(_this.form.Enterprise_Info_SerialNumber)
      console.log(_this.form.Children.integral_unitprice_detail)
      _this.form.Children.integral_unitprice_detail.forEach(item => {
        _this.shop.forEach(item1 => {
          if (item.Article_SerialNumber == item1.Article_SerialNumber) {
            _this.Enterprise.push(item1.Enterprise_Info_SerialNumber);
          }
        })
      })
      _this.Enterprise = _this.Enterprise.filter(item => {
        return item != _this.form.Enterprise_Info_SerialNumber
      })
      let newEnterprise_Info_SerialNumberList = Array.from(new Set(_this.Enterprise))
      // if (_this.form.Children.sales_unitprice_detail[0].Unit_Price == '' || _this.form.Children.sales_unitprice_detail[0].Article_SerialNumber == '' || _this.form.Children.sales_unitprice_detail[0].Sales_Unit_Price == '' || _this.form.Children.sales_unitprice_detail[0].Distribute == '' || _this.form.Children.sales_unitprice_storescope[0].Store_SerialNumber == '') {
      //   return _this.$message.error("请完善信息")
      // }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.loading = true

          let TimeDays = (1000 * 60) * 60 * 24
          //1.获取第一次补货时间
          let time = `${_this.form.Start_Date.substring(0, 10)} ${_this.always}`;
          console.log(time)
          console.log(_this.form.Start_Date)
          if (+new Date(time) < +new Date(_this.form.Start_Date)) {
            time = _this.formatTime(+new Date(time) + TimeDays)
          }
          //2.判断结算时间是否小于第一次补货，如果小于等于生成1次库存，开始结束时间与主表相同
          //如果大于，第一次自动生成开始时间到补货时间，第二次自动生成判断剩余时间是否小于24小时，如果小于从补货时间开始，主表结束时间结束
          //如果大于补货时间开始到次日补货时间前1秒结束，第三次自动生成以此类推
          _this.form.Children.integral_unitprice_storescope.forEach(item1 => {
            _this.form.Children.integral_unitprice_detail.forEach(item => {
              if (item.Sign == "无货货主") {
                _this.Automatic(item, item1.Store_SerialNumber, _this.form.Start_Date, _this.form.End_Date, time)
              } else if (item.Sign == "有货货主") {
                item.Children.integral_unitprice_stock.push({
                  Integral_Unit_Price_Stock_SerialNumber: "",
                  Integral_Unit_Price_Detail_SerialNumber: "",
                  Store_SerialNumber: item1.Store_SerialNumber,
                  Start_Date: _this.form.Start_Date,
                  End_Date: _this.form.End_Date,
                  Distribute: parseInt(item.Distribute),
                  Stock_Remain: parseInt(item.Distribute),
                  Stock_Sell: 0
                })
              }
            })
          })
          _this.form.Children.integral_unitprice_detail.forEach(item => {
            if (item.Sign == "有货货主") {
              item.Children['integral_unitprice_warehouse'] = []
              item.isWarehouse.forEach(i => {
                item.Children.integral_unitprice_warehouse.push({
                  Integral_Unit_Price_Warehouse_SerialNumber: '',
                  Integral_Unit_Price_Detail_SerialNumber: '',
                  Warehouse_SerialNumber: i,
                })
              })
            }
          })
          console.log(_this.form)
          $.ajax({
            url: DomainName + '/getAddAction?token=' + $.cookie("token"),
            type: 'POST',
            data: {
              Data: JSON.stringify({
                integral_unitprice: [_this.form]
              }),
              // Enterprise_Info_SerialNumber: JSON.stringify(newEnterprise_Info_SerialNumberList),
            },
            success: function (res) {
              if (res.Status === 'success') {
                _this.$message.success("操作成功")
                // window.location.href = './IntegralUnitprice.html'
                window.history.go(-1);
              } else {
                _this.$message.error("操作失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    Change_Column_Type() {
      // if(this.form.Activity=='0'){
        this.column.forEach((item, index) => {
          item.options.forEach(item1 => {
            this.form.Children.iintegral_unitprice_column.forEach
            (item2 => {
              if (index == 0 && item2.Column_Id == item1.Column_Id) {
                item2.Column_Type = '0'
              } else if (index == 1 && item2.Column_Id == item1.ShopColumn_Id) {
                item2.Column_Type = '1'
              }
            })
          })
        })
      // }else if (this.form.Activity=='1'){
        // this.form.Children.sales_unitprice_column.forEach(item => {
          // item.Column_Type = '1'
        // })
      // }
    },
    submitForm1() {
      let _this = this
      _this.loading = true
      //无货货主商品自动按照执行天数，生成货物
      let integral_unitprice_storescope = []
      let integral_unitprice_column = []
      var reg = RegExp(/C1/);
      this.Store_SerialNumber.forEach(item => {
        integral_unitprice_storescope.push({
          Integral_Unit_Price_StoreScope_SerialNumber: "",
          Integral_Unit_Price_SerialNumber: '',
          Store_SerialNumber: item,
        })
      })
      this.Column_Id.forEach(item => {
        integral_unitprice_column.push({
          Integral_Unit_Price_Column_SerialNumber: '',
          Integral_Unit_Price_SerialNumber: '', //单价流水号
          ShopColumn_Id: item,
          Column_Type: reg.test(item) ? '1' : '0', //栏目属性
        })
      })
      let obj = {
        Integral_Unit_Price_SerialNumber: "",
        Integral_Date: this.Start_Date,
        End_Date: this.End_Date,
        Row_Status: '2',
        Enterprise_Info_SerialNumber: $.cookie("enterprise"),
        Children: {
          integral_unitprice_detail: [],
          integral_unitprice_storescope,
          integral_unitprice_column,
        }
      }
      this.getAddAction(this.tableData, obj)
    },
    getAddAction(data, obj) {
      const _this = this;
      if (data.length > 2) {
        let arr1 = data.filter((item, index) => index < 2)
        let arr2 = data.filter((item, index) => index >= 2)
        obj.Children.integral_unitprice_detail = arr1
        console.log(obj);
        console.log(arr1);
        console.log(arr2);
        this.Add(obj, () => {
          _this.getAddAction(arr2, obj)
        })
      } else {
        this.Add(data, () => {
          _this.$message.success('提交成功')
          _this.loading = false
          window.location.href = './Goods.html'
        })
      }
    },
    Add(arr, callback) {
      const _this = this
      let TimeDays = (1000 * 60) * 60 * 24
      let time = `${arr.Start_Date.substring(0, 10)} ${this.always}`;
      if (+new Date(time) < +new Date(arr.Start_Date)) {
        time = this.formatTime(+new Date(time) + TimeDays)
      }
      arr.Children.integral_unitprice_storescope.forEach(function (item1, index) {
        arr.Children.integral_unitprice_detail.forEach(function (item, index) {
          if (item.Sign == "无货货主") {
            _this.Automatic(item, item1.Store_SerialNumber, arr.Start_Date, arr.End_Date, time)
          }
        })
      })
      $.ajax({
        type: 'POST',
        url: DomainName + '/getAddAction?token=' + $.cookie('token'),
        data: {
          Data: JSON.stringify({ integral_unitprice: arr })
        },
        complete: function (XMLHttpRequest) {
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        },
        success: function (Result) {
          if (Result.Status == 'success') {
            console.log('提交成功');
            callback();
          }
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        dataType: "json"
      });
    },
    Filter(i, row) {
      if (i == 2) {
        this.tableData = this.tableData.filter(item => item.Abnormal && item.Distribute > 0 && item.Integral_Unit_Price > 0)
        this.$message.success("已筛选掉异常数据")
      }
    },
    tableCellStyle({ row, column, rowIndex, columnIndex }) {
      if (!row.Abnormal) return { backgroundColor: '#E6A23C' }
    },
  },
  created() {
    this.getData();
  }
})